package service;

import appexception.AppException;
import com.fasterxml.jackson.databind.ObjectMapper;
import unit.JSONResponse;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.sql.SQLException;

/**
 * @program: wsn_blog1
 * @description
 * @author:王松年
 * @creat: 2021-07-13 11:04:27
 **/
public abstract class BaseService extends HttpServlet {
    protected ObjectMapper objectMapper = new ObjectMapper();
    protected JSONResponse json = new JSONResponse();
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doPost(req, resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.setCharacterEncoding("utf-8");
        resp.setCharacterEncoding("utf-8");
        resp.setContentType("application/json");
        try{
            json.setSuccess(false);
            //业务处理部分
            query(req,resp);
            //业务处理成功
            json.setSuccess(true);
        }catch (Exception e) {
            e.printStackTrace();
            if (e instanceof AppException) {
                AppException appException = (AppException) e;
                json.setCode(appException.getCode());
                json.setMessage(appException.getMessage());
            } else {
                json.setMessage("未知错误，请联系系统管理员！");
                json.setCode("LOGIN000");
            }
        } finally {
            resp.getWriter().println(objectMapper.writeValueAsString(json));
        }
    }
    protected abstract void query(HttpServletRequest req, HttpServletResponse resp) throws SQLException, IOException;
}